<template>
  <el-card class="tab-card">
    <div class="statisticsList">
      <el-dropdown placement="bottom">
        <span class="itemsta el-dropdown-link">
          <i :style="{background:'#67C23A'}"></i>
          累计埋点:
          <span>{{staticComputed(statisticsList.sumCountlist,'pageSumCount')}}</span>
        </span>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item v-for="(_i,_in) in statisticsList.sumCountlist" :key="_in">
            <span class="leftpagenum">{{_i.pageName}} :</span>
            <span class="rightpagenum">{{_i.pageSumCount}}</span>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <el-dropdown placement="bottom">
        <span class="itemsta el-dropdown-link">
          <i :style="{background:'#00BFBF'}"></i>
          已埋点:
          <span>{{staticComputed(statisticsList.alreadyCountlist,'pageAlreadySumCount')}}</span>
        </span>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item v-for="(_i,_in) in statisticsList.alreadyCountlist" :key="_in">
            <span class="leftpagenum">{{_i.pageName}} :</span>
            <span class="rightpagenum">{{_i.pageAlreadySumCount}}</span>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <el-dropdown placement="bottom">
        <span class="itemsta el-dropdown-link">
          <i :style="{background:'#E6A23C'}"></i>
          待埋点:
          <span>{{staticComputed(statisticsList.notCountlist,'pageNotSumCount')}}</span>
        </span>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item v-for="(_i,_in) in statisticsList.notCountlist" :key="_in">
            <span class="leftpagenum">{{_i.pageName}} :</span>
            <span class="rightpagenum">{{_i.pageNotSumCount}}</span>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
    <!--		<el-button type="primary" size="mini" class="btn-float-right" @click="handleShowDownLoad" v-if="activeName == 'first'">下载埋点</el-button>-->
    <el-tabs v-model="activeName" :style="{position:'relative'}" @tab-click="handleClick">
      <el-tab-pane label="页面/全局区块埋点" name="first">
        <div class="clearfix">
          <div class="left-module">
            <el-select v-model="pageId" size="mini" @change="handleChangePage">
              <el-option
                v-for="item in pageNavigate"
                :value="item.id"
                :label="item.pageName"
                :key="item.id"
              ></el-option>
            </el-select>
            <pic-upload-module :picInfo="picInfo" :action="['details']"></pic-upload-module>
          </div>
          <div class="right-module">
            <div class="content" v-if="pageTableData.length === 0">暂无埋点</div>
            <div class="content" v-else>
              <el-card v-for="item in pageTableData" class="bury-card" :key="item.trackId">
                <div slot="header" class="content">
                  <span>{{item.trackName}}</span>
                  <confirm-btn
                    :status="item.processStatus"
                    :id="item.id"
                    v-if="confirmBtnType === 'edit'"
                  ></confirm-btn>
                </div>
                <div>
                  <div class="item clearfix">
                    <div class="left">埋点提示：</div>
                    <div class="right">
                      请根据下面的说明，在代码中
                      <span
                        :class="'requirement-type-' + item.requirementType"
                      >{{$handleRequirementType(item.requirementType) || "--"}}</span>
                      埋点
                    </div>
                  </div>
                  <div class="item clearfix">
                    <div class="left">埋点时机：</div>
                    <div class="right">{{item.extMessage ? item.extMessage.trackOpportunity : "--"}}</div>
                  </div>
                  <div class="item clearfix">
                    <div class="left">代码示例：</div>
                    <div class="right">
                      <pre>{{item.demoCode}}</pre>
                    </div>
                  </div>
                </div>
              </el-card>
              <el-pagination
                class="tab-pagination"
                @size-change="handleSizePage"
                @current-change="handleCurrentPage"
                :current-page="pageSearch.currentPage"
                :page-sizes="[5, 10, 20, 30, 40]"
                :page-size="pageSearch.pageSize"
                background
                layout="total, prev, pager, next, sizes, jumper"
                :total="pageSearch.total"
              ></el-pagination>
            </div>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="无位置埋点" name="second">
        <div v-if="noPageTableData.length === 0">暂无埋点</div>
        <div v-else>
          <el-card v-for="item in noPageTableData" class="bury-card" :key="item.trackId">
            <div slot="header" class="content">
              <span>{{item.trackName}}</span>
              <confirm-btn
                :status="item.processStatus"
                :id="item.id"
                v-if="confirmBtnType === 'edit'"
              ></confirm-btn>
            </div>
            <div>
              <div class="item clearfix">
                <div class="left">埋点提示：</div>
                <div class="right">
                  请根据下面的说明，在代码中
                  <span
                    :class="'requirement-type-' + item.requirementType"
                  >{{$handleRequirementType(item.requirementType) || "--"}}</span>
                  埋点
                </div>
              </div>
              <div class="item clearfix">
                <div class="left">埋点时机：</div>
                <div class="right">{{item.extMessage ? item.extMessage.trackOpportunity : "--"}}</div>
              </div>
              <div class="item clearfix">
                <div class="left">代码示例：</div>
                <div class="right">
                  <pre>{{item.demoCode}}</pre>
                </div>
              </div>
            </div>
          </el-card>
          <el-pagination
            class="tab-pagination"
            @size-change="handleSize"
            @current-change="handleCurrent"
            :current-page="noPageSearch.currentPage"
            :page-sizes="[5, 10, 20, 30, 40]"
            :page-size="noPageSearch.pageSize"
            background
            layout="total, prev, pager, next, sizes, jumper"
            :total="noPageSearch.total"
          ></el-pagination>
        </div>
      </el-tab-pane>
    </el-tabs>
    <el-dialog
      @close="downloadVisible = false;"
      class="download-dialog"
      :visible="downloadVisible"
      title="下载埋点"
    >
      <p>提示：请选择位置，可多选</p>
      <div class="page-content">
        <span>选择位置：</span>
        <el-select
          v-model="pageIds"
          size="mini"
          multiple
          clearable
          filterable
          @change="handlePageSelect"
        >
          <el-option
            v-for="item in pageNavigate"
            :value="item.pageId"
            :label="item.pageName"
            :key="item.pageId"
          ></el-option>
        </el-select>
        <el-checkbox v-model="pageCheckBox" @change="handleCheck">全选</el-checkbox>
      </div>
      <div class="btn-group">
        <el-button type="primary" size="mini" @click="handleDownload">下载</el-button>
        <el-button size="mini" @click="downloadVisible = false;">取消</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
export default {
  name: "developEdit",
  data() {
    return {
      id: null,
      sdkType: null, // 埋点需求下属性
      statisticsList: {
        alreadyCountlist: [],
        notCountlist: [],
        sumCountlist: []
      }, // 统计信息结果集
      activeName: "first",
      activeCount: 0,
      pageId: null,
      pageNavigate: [],
      pageRow: {},
      picInfo: {
        url: "",
        iconPosition: []
      },
      pageSearch: {
        currentPage: 1,
        pageSize: 5,
        total: 0
      },
      pageTableData: [],
      noPageSearch: {
        currentPage: 1,
        pageSize: 5,
        total: 0
      },
      noPageTableData: [],
      confirmBtnType: "",
      pageCheckBox: false,
      pageIds: [],
      downloadVisible: false
    };
  },
  components: {
    // ConfirmBtn
  },
  created() {
    console.log("新接口哈哈哈");
  },
  mounted() {
    let { id, type, sdkType } = this.$route.params;
    this.id = unescape(id);
    this.sdkType = unescape(sdkType);
    this.confirmBtnType = type;
    this.handleQueryStatisticsList(); // 获取统计信息列表
    this.handleQueryPageNavigate();
  },
  methods: {
    staticComputed(arr, key) {
      let num = 0;
      arr.map(_i => {
        num += _i[key] ? _i[key] : 0;
      });
      return num;
    },
    // 获取统计信息列表
    async handleQueryStatisticsList() {
      let res = await this.$pageApi.statisticsList({
        requirementId: this.id,
        sdkType: this.sdkType,
        showDev: true
      });
      if (res&&res.success) {
        this.statisticsList = res.value;
      }
    },
    // 下载dialog
    handleShowDownLoad() {
      this.downloadVisible = true;
      this.pageCheckBox = false;
      this.pageIds = [];
    },
    handleCheck(val) {
      let ids = [];
      if (val) {
        this.pageNavigate.forEach(item => {
          ids.push(item.pageId);
        });
      } else {
        ids = [];
      }
      this.pageIds = ids;
    },
    handlePageSelect(val) {
      if (val.length == this.pageNavigate.length) {
        this.pageCheckBox = true;
      } else {
        this.pageCheckBox = false;
      }
    },
    // 下载埋点
    async handleDownload() {
      // let data = {
      // 	pageIds: this.pageIds,
      // 	requirementId: this.id,
      // 	showDev: true,
      // 	sdkType: this.pageRow.sdkType
      // };
      // 测试数据
      let data = {
        requirementId: "10000065",
        pageIds: ["gdfwsy"],
        sdkType: 1,
        showDev: true
      };
      // let res = await this.$eventApi.eventDownload(data);
      let res = await this.http.post("/behavior/track/export", data, {
        responseType: "blob"
      });
      // let res = await this.http({
      // 	url: '/behavior/track/export',
      // 	method: 'post',
      // 	data,
      // 	responseType: 'blob'
      // });
      if (res) {
        console.log(res, "res");
        let blob = new Blob([res.data]); //application/vnd.openxmlformats-officedocument.spreadsheetml.sheet这里表示xlsx类型
        let downloadElement = document.createElement("a");
        let href = window.URL.createObjectURL(blob); //创建下载的链接
        downloadElement.href = href;
        // downloadElement.download = "";
        downloadElement.download = "埋点列表.xls"; //下载后文件名
        document.body.appendChild(downloadElement);
        downloadElement.click(); //点击下载
        document.body.removeChild(downloadElement); //下载完成移除元素
        window.URL.revokeObjectURL(href); //释放掉blob对象
      }
    },
    // 获取导航
    async handleQueryPageNavigate() {
      let res = await this.$pageApi.pageNavigate({
        requirementId: this.id
      });
      if (res) {
        let { pageNavigateList } = res.value;
        this.pageNavigate = pageNavigateList;
        if (pageNavigateList.length > 0) {
          let id = pageNavigateList[0].id;
          this.pageId = id;
          this.handleChangePage(id);
        }
      }
    },
    handleChangePage(val) {
      this.handleQueryPage(val);
    },
    async handleQueryPage(id) {
      let res = await this.$pageApi.pageQuery({ id });
      if (res) {
        this.pageRow = res.value;
        this.picInfo = {
          url: res.value.imageUrl,
          iconPosition: res.value.iconPosition
        };
        this.handleEventList();
      }
    },
    // 页面埋点
    handleCurrentPage(page) {
      this.pageSearch.currentPage = page;
      this.handleEventList();
    },
    handleSizePage(size) {
      this.pageSearch.currentPage = 1;
      this.pageSearch.pageSize = size;
      this.handleEventList();
    },
    // 无位置埋点
    handleCurrent(page) {
      this.noPageSearch.currentPage = page;
      this.handleEventList();
    },
    handleSize(size) {
      this.noPageSearch.currentPage = 1;
      this.noPageSearch.pageSize = size;
      this.handleEventList();
    },
    // 埋点列表
    async handleEventList() {
      let data = {};
      if (this.activeName === "first") {
        let { currentPage, pageSize } = this.pageSearch;
        data = {
          currentPage,
          pageSize,
          requirementId: this.id,
          pageId: this.pageRow.pageId,
          sdkType: this.pageRow.sdkType,
          showDev: true
        };
      } else if (this.activeName === "second") {
        let { currentPage, pageSize } = this.noPageSearch;
        data = {
          currentPage,
          pageSize,
          hasPosition: true,
          requirementId: this.id,
          showDev: true
        };
      }
      let res = await this.$eventApi.eventList(data);
      if (res) {
        let { list, total } = res.value;
        if (this.activeName === "first") {
          this.pageTableData = list;
          this.pageSearch.total = total;
        } else {
          this.noPageTableData = list;
          this.noPageSearch.total = total;
        }
      }
    },
    // 切换tab
    handleClick(tab) {
      let { name } = tab;
      this.activeName = name;
      if (name === "second") {
        if (this.activeCount === 0) {
          this.handleEventList();
        }
        this.activeCount++;
      }
    }
  }
};
</script>

<style lang="scss">
.leftpagenum {
  display: inline-block;
  min-width: 2rem;
  text-indent: 10px;
  font-size: 12px;
  letter-spacing: 2px;
}
.rightpagenum {
  display: inline-block;
  font-size: 12px;
}
.statisticsList {
  position: absolute;
  right: 0;
  width: 9rem;
  top: 0;
  display: flex;
  align-items: center;
  justify-content: space-evenly;
  height: 40px;

  cursor: pointer;
  z-index: 10;
  .itemsta {
    display: inline-block;
    cursor: pointer;
    height: 40px;
    line-height: 40px;
    font-size: 14px;
    letter-spacing: 2px;
    i {
      display: inline-block;
      height: 8px;
      width: 8px;
      line-height: 40px;
      opacity: 0.6;
      border-radius: 50%;
    }
    span {
      cursor: pointer;
      font-size: 10px;
      padding: 0 4px;
    }
  }
}
.el-card.tab-card .el-card__body {
  position: relative;
}
.tab-card {
  position: relative;
  .el-tab-pane {
    box-sizing: border-box;

    .left-module {
      width: 25%;
      float: left;
      /*height: 300px;*/
      .el-select {
        width: 100%;
        margin-bottom: 15px;
      }

      .pic-upload-module {
        height: 300px;
      }
    }

    .right-module {
      padding-left: 25%;

      & > .content {
        padding-left: 20px;
      }
    }
  }

  .bury-card {
    &:not(:first-child) {
      margin-top: 5px;
    }

    .el-card__header {
      background-color: #f8f8f9;
    }

    .item {
      padding: 8px 0;

      & > .left {
        width: 80px;
        float: left;
        padding-left: 20px;
      }

      .tip {
        position: relative;

        & > i {
          position: absolute;
          left: 0;
          top: 50%;
          transform: translateY(-50%);
          color: #fd4f54;
        }
      }
    }
  }

  .tab-pagination.el-pagination {
    margin: 20px 0;
  }
}
</style>
<style scoped lang="scss">
.btn-float-right {
  position: absolute;
  right: 20px;
  top: 8px;
  cursor: pointer;
  z-index: 10;
}
.download-dialog {
  .page-content {
    margin-bottom: 15px;
    .el-select {
      width: 300px;
    }
    .el-checkbox {
      margin-left: 10px;
    }
  }
  .btn-group {
    text-align: right;
    .el-button {
      margin-left: 8px;
    }
  }
}
</style>
